# encoding=utf8
'''
    部署在思迈特服务器的接口主函数
'''
import requests
from flask import Flask, request, jsonify
import ast
import json

app = Flask(__name__)
host = 'http://10.10.14.14'

def Str2Obj(string):
    '''
    将字符串转为python中的对象
    :param string: 原字符串
    :return: python对象/字符串
    '''
    try:
        obj = ast.literal_eval(string)
        return obj
    except Exception as e:
        return string

def FusionMethod1(End2End_res,IntentReg_res):
    '''
    融合方法1：进行模糊维度的融合，减少用户的选择量
    :return: 用户待选择的维度
    '''
    # 获取sel维度name
    sel = []
    sel_name = []
    End2End_data = End2End_res["data"]
    sel = End2End_data[0]['sel']

    for item in sel:
        sel_name.append(item["name"])
    temp_end2end = set(sel_name)
    # 融合1——如果sel_name和每个待选择的维度列表存在交集并且交集元素为1，则该模糊维度不需要用户进行选择
    for item in IntentReg_res["data"]:
        candidates = Str2Obj(item["candidates"])
        temp_intent = set(candidates)
        intersection = temp_intent & temp_end2end
        if len(intersection) == 1:
            item["candidates"] = list(intersection)
    return jsonify(IntentReg_res)



@app.route('/IntentRegEngine', methods=["POST"])
def IntentRegEngine():
    # 接口url
    OptReg_request_url = host+":5001/OptRecognition"
    IntentReg_request_url = host+":5002/getSQLs_error"
    End2End_request_url = host+":5003"
    KB_request_url = host+":5004/problem_normalization"


    # 添加请求头，需要就传
    header = {
        "Content-Type": "application/json"
    }
    formal_question = ""
    # 解析前端传输数据
    front_data = request.get_json()
    print(front_data)
    status = front_data['status']
    data = front_data['data']
    question = data['question']

    if status == 200:
        # 操作识别
        OptReg_input_json = {
            "status": status,
            "data":
                {
                    "instruction": question
                }
        }
        OptReg_response = requests.post(url=OptReg_request_url, json=OptReg_input_json, headers=header)
        # 格式转换
        OptReg_output = ast.literal_eval(OptReg_response.content.decode('utf-8'))

        if OptReg_output['is_opt'] == 'y':
            # 如果是操作问句则直接返回识别结果 (如“打开财务报表”)
            res = {
                "status": 302,
                "data": [
                    [
                        {
                            "key": "operation",
                            "content": str(OptReg_output['exact_opt'])
                        }
                    ]
                ]
            }
            return jsonify(res)

        # 知识图谱规范化
        KB_input_json = {
            "status": status,
            "data":
                {
                    "question": question
                }
        }

        KB_response = requests.post(url=KB_request_url, json=KB_input_json)
        # 格式转换
        # unicode_escape避免出现中文乱码的问题
        KB_output = ast.literal_eval(KB_response.content.decode('unicode_escape'))
        KB_data = KB_output['data']
        formal_question = KB_data['question']
        tag = KB_data['tag']
        recommended_queries = KB_data['recommended_queries']
        if len(recommended_queries) != 0:
            res = {
                "status": 301,
                "data": recommended_queries
            }
            return res

        # 意图识别
        IntentReg_input_json = {
            "status": status,
            "data": {
                "question": formal_question
            }
        }

        IntentReg_response = requests.post(url=IntentReg_request_url, json=IntentReg_input_json)

        IntentReg_res = json.loads(IntentReg_response.content.decode('utf-8'))
        if IntentReg_res['status'] == 300:
            # 需要用户进行维度选择
            # 端到端
            End2End_input_json = {
                "status": status,
                "data": {
                    "question": formal_question
                }
            }
            End2End_response = requests.post(url=End2End_request_url, json=End2End_input_json)
            # End2End_res = ast.literal_eval(End2End_response.content.decode('utf-8'))
            End2End_res = json.loads(End2End_response.content.decode('utf-8'))
            return FusionMethod1(End2End_res, IntentReg_res)

    elif status == 300:
        # 用户选择完模糊维度后返回
        IntentReg_response = requests.post(url=IntentReg_request_url, json=front_data)
        IntentReg_res = json.loads(IntentReg_response.content.decode('utf-8'))
    elif status == 301:
        # 用户选择完推荐问句后返回
        input_json = {
            "status": 200,
            "data": {
                "question": question
            }
        }
        IntentReg_response = requests.post(url=IntentReg_request_url, json=input_json)
        # IntentReg_res = ast.literal_eval(IntentReg_response.content.decode('utf-8'))
        IntentReg_res = json.loads(IntentReg_response.content.decode('utf-8'))

        if IntentReg_res['status'] == 300:
            # 需要用户进行维度选择
            # 端到端
            End2End_input_json = {
                "status": status,
                "data": {
                    "question": formal_question if formal_question != "" else question
                }
            }
            End2End_response = requests.post(url=End2End_request_url, json=End2End_input_json)
            # End2End_res = ast.literal_eval(End2End_response.content.decode('utf-8'))
            End2End_res = json.loads(End2End_response.content.decode('utf-8'))
            return FusionMethod1(End2End_res, IntentReg_res)

    return jsonify(IntentReg_res)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
